package pkg

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/spf13/viper"
	"mime/multipart"
)

func CreateOssClient(handler func(bucket *oss.Bucket, bucketName, endpoint string) (string, error)) (string, error) {
	ak := viper.GetString("oss.ak")
	sk := viper.GetString("oss.sk")
	endpoint := viper.GetString("oss.endpoint")
	bucketName := viper.GetString("oss.bucketName")
	client, err := oss.New(endpoint, ak, sk)
	if err != nil {
		return "", err
	}

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return "", err
	}

	return handler(bucket, bucketName, endpoint)
}

func UploadFile(filename string, fileInfo *multipart.FileHeader) (string, error) {
	return CreateOssClient(func(bucket *oss.Bucket, bucketName, endpoint string) (string, error) {
		file, err := fileInfo.Open()
		if err != nil {
			return "", err
		}
		defer file.Close()

		err = bucket.PutObject(filename, file)
		if err != nil {
			return "", err
		}

		return fmt.Sprintf("https://%s.%s/%s", bucketName, endpoint, filename), nil
	})

}
